//
//  UserHomeTableViewController.swift
//  甜言蜜语
//
//  Created by 王剑伟 on 16/6/14.
//  Copyright © 2016年 wl. All rights reserved.
//

import UIKit
import SVProgressHUD
class UserHomeTableViewController: UITableViewController,RGFadeDelegate {
    
    var userId: Int? {
        didSet {
            self.tableView.mj_header.beginRefreshing()
        }
    }
    
    var model: UserHomeModel? {
        didSet {
            self.homeHeadView.model = model?.userHeadModel
            self.tableView.reloadData()
        }
    }
    var rgFadeView: RGFadeView?
    var homeHeadView = UserHomeHeadView.create()
    var followOrCancel: Bool?
    var msg: regiestInfo?
    var requistID: String = ""
    var height:CGFloat = 300.0
    override func viewDidLoad() {
        super.viewDidLoad()
        publicMethod.setHUDStyle()
        self.title = "个人主页"
        
         let font = UIFont(name: "Helvetica", size: 16)
        
        if self.model?.userHeadModel.signature != nil{
             height = publicMethod.getLabHeigh((self.model?.userHeadModel.signature)!, font: font!, width: SCREEN_WIDTH - 16) + 300.0
        }
        
        homeHeadView.frame.size.height = height
        
        self.tableView.tableHeaderView = homeHeadView
        homeHeadView.followBtn.addTarget(self, action: #selector(UserHomeTableViewController.fllowBtnClicked(_:)), forControlEvents: UIControlEvents.TouchUpInside)
        
        homeHeadView.fansBtn.addTarget(self, action: #selector(self.fansBtnClicked(_:)), forControlEvents: UIControlEvents.TouchUpInside)
        
        homeHeadView.followOrCancelBtn.addTarget(self, action: #selector(self.followOrCancelBtnClicked(_:)), forControlEvents: UIControlEvents.TouchUpInside)
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(UserHomeTableViewController.zanBtnClicked_noti(_:)), name: userZan_noti, object: nil)
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(UserHomeTableViewController.shareBtnClicked_noti(_:)), name: userShare_noti, object: nil)
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(UserHomeTableViewController.replyBtnClicked_noti(_:)), name: userReply_noti, object: nil)

        
        self.tableView.mj_header = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: #selector(UserHomeTableViewController.requestInfo))
        
//        self.tableView.mj_footer = MJRefreshAutoNormalFooter(refreshingTarget: self, refreshingAction: #selector(UserHomeTableViewController.requestMoreInfo))
    }
    override func viewWillDisappear(animated: Bool) {
        SVProgressHUD.dismiss()
        super.viewWillDisappear(animated)
    }
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.navigationBar.barTintColor = NAVIGATIONBAR_RED_COLOR
        self.tabBarController?.tabBar.hidden = true
    }

    deinit {
        //移除通知
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    // MARK: - Table view data source

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        var count = 0
        
        if self.model != nil
        {
            count = self.model!.commentList.count
        }
        
        return count
    }

    override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        if(cell.respondsToSelector(Selector("setSeparatorInset:"))) {
            cell.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0)
        }
        if(cell.respondsToSelector(Selector("setLayoutMargins:"))) {
            cell.layoutMargins = UIEdgeInsetsMake(0, 0, 0, 0)
        }
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("UserHomeTableViewCell", forIndexPath: indexPath) as! UserHomeTableViewCell
        
        cell.model = self.model?.commentList[indexPath.row]
        
        return cell
    }
    
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        let font = UIFont(name: "Helvetica", size: 16)


        let height = publicMethod.getLabHeigh((self.model?.commentList[indexPath.row].message)!, font: font!, width: SCREEN_WIDTH - 16)
        
        return 180 + height
    }
    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        let vc = self.storyboard?.instantiateViewControllerWithIdentifier("ReplyVC") as! ReplyVC
        vc.type = "行业"
      
        vc.id = (self.model?.commentList[indexPath.row].id)!
        self.navigationController?.pushViewController(vc, animated: true)

    }
    
    //关注按钮点击事件
    func fllowBtnClicked(sender: UIButton){
        let vc = self.storyboard?.instantiateViewControllerWithIdentifier("UserFollowAndFans") as! UserFollowAndFans
        vc.UserID = String(self.model!.userHeadModel.id)
        vc.type = "1"
        self.navigationController?.pushViewController(vc, animated: true)
        
        
    }
    //粉丝按钮点击事件
    func fansBtnClicked(sender: UIButton){
        let vc = self.storyboard?.instantiateViewControllerWithIdentifier("UserFollowAndFans") as! UserFollowAndFans
        vc.UserID = String(self.model!.userHeadModel.id)
        vc.type = "2"
        self.navigationController?.pushViewController(vc, animated: true)
        
    }
    //取消或者关注点击事件
    func followOrCancelBtnClicked(sender: UIButton){
        if ApplicationDelegate.isLogin(){
            if model?.userHeadModel.isMe == true{
                if !publicMethod.isComplete(){
                    let sb = UIStoryboard.init(name: "Login", bundle: nil)
                    let vc = sb.instantiateViewControllerWithIdentifier("ChooseTypeTableViewController") as! ChooseTypeTableViewController
                    
                    self.navigationController?.pushViewController(vc, animated: true)
                }else{
                    let type = (NSUserDefaults.standardUserDefaults().objectForKey("k_UD_type")) as! String
                    
                    if type == "个人"{
                        let sb = UIStoryboard.init(name: "MySelf", bundle: nil)
                        let vc = sb.instantiateViewControllerWithIdentifier("UserInfoTC") as! UserInfoTC
                        self.hidesBottomBarWhenPushed = true
                        self.navigationController?.pushViewController(vc, animated: true)
                        self.hidesBottomBarWhenPushed = false
                    }
                    if type == "企业"{
                        let sb = UIStoryboard.init(name: "MySelf", bundle: nil)
                        let vc = sb.instantiateViewControllerWithIdentifier("UserCompnayVC") as! UserCompnayVC
                        
                        vc.type = "企业"
                        self.hidesBottomBarWhenPushed = true
                        self.navigationController?.pushViewController(vc, animated: true)
                        self.hidesBottomBarWhenPushed = false
                    }
                    if type == "美容院"{
                        let sb = UIStoryboard.init(name: "MySelf", bundle: nil)
                        let vc = sb.instantiateViewControllerWithIdentifier("UserBeautyVC") as! UserBeautyVC
                        
                        vc.type = "美容院"
                        self.hidesBottomBarWhenPushed = true
                        self.navigationController?.pushViewController(vc, animated: true)
                        self.hidesBottomBarWhenPushed = false
                    }
                    
                
            }
                
            }else{
                if model?.userHeadModel.isguanzhu == true{
                    self.followOrCancel = false
                }else{
                    self.followOrCancel = true
                }
                
                DataTool.followOrCancel(String(model!.userHeadModel.id), isguanzhu: self.followOrCancel!, completionHandler: { (newModel) in
                    guard newModel != nil else {
                        return
                    }
                    self.msg = newModel
                    self.requestInfo()
                    SVProgressHUD.showSuccessWithStatus(self.msg?.msg)
                })
            }
            
        }else{
            let sb = UIStoryboard(name: "Login", bundle: nil)
            let vc = sb.instantiateViewControllerWithIdentifier("LoginViewController")
            self.navigationController?.pushViewController(vc, animated: true)
        }
    }
    

    /**
     下拉刷新，加载最新数据
     */
    func requestInfo() {
        
        DataTool.loadUserHomeData(self.userId!, completionHandler: { (userHomeData) -> Void in
            self.tableView.mj_header.endRefreshing()
            guard let homeData = userHomeData else {
                return
            }
            self.model = homeData
        })
    }
    
    //MARK:noti
    func zanBtnClicked_noti(notification:NSNotification){
        
       // let id = notification.object?.valueForKey("id") as! String
        //let number = notification.object?.valueForKey("number") as! String
//        DataTool.supposeComment(Int(id)!, completionHandler: { (isSuccess) -> Void in
//            if isSuccess {
//                
//                //let value = Int(number)! + 1
//                
//                //self.supposeNumLbl.text = String(value)
//                //self.supposeBtn.setImage(UIImage(named: "zan_selected"), forState: UIControlState.Normal)
//            } else {
//                //sender.deselect()
//            }
//        })

        
    }

    func shareBtnClicked_noti(notification:NSNotification){
        
        let id = notification.object?.valueForKey("id") as! String
        self.requistID = id
        
        print("share")
        
    }
    func replyBtnClicked_noti(notification:NSNotification){
        
        let id = notification.object?.valueForKey("id") as! String
        
        self.tableView.setContentOffset(CGPointMake(0, 0), animated: false)

        self.requistID = id
        
        if (rgFadeView == nil) {
            rgFadeView = RGFadeView.init(frame: kScreen_frame)
            //rgFadeView?.docid = newsDetailModel?.docid
            rgFadeView?.delegate = self
            self.view.addSubview(rgFadeView!)
        }
        rgFadeView?.msgTextView.becomeFirstResponder()
    }
    //MARK:RGFadeViewDelegate
    func sendBtnDown(text: String) {
        
        let jsonData = ["docid": self.requistID, "message": text]
        
        DataTool.sendComment(jsonData,type: "", completionHandler: { (isSuccess) -> Void in
            if isSuccess {
                SVProgressHUD.showSuccessWithStatus("回复成功")
               
                self.requestInfo()
            } else {
                SVProgressHUD.showErrorWithStatus("回复失败")
              
            }
        })
    }

        /**
     上拉刷新，加载更多数据
     */
    func requestMoreInfo() {
        
//        DataTool.loadNewsData("http://192.168.3.153:8080/hzp/service/infomationjson", newsKey: "最新推荐") { (newsArray) -> Void in
//            
//            self.tableView.mj_footer.endRefreshing()
//            guard let newDataes = newsArray else {
//                return
//            }
//            self.newsModelArray! += newDataes
//        }
    }

}

    